<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
			label-width="68px">
			<el-form-item label="健身馆名称" prop="gymName">
				<el-input v-model="queryParams.gymName" placeholder="请输入健身馆名称" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="地址" prop="location">
				<el-input v-model="queryParams.location" placeholder="请输入地址" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="是否开放" prop="state">
				<el-select v-model="queryParams.state" placeholder="请选择是否开放" clearable>
					<el-option v-for="dict in dict.type.sys_gym_open" :key="dict.value" :label="dict.label"
						:value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
					v-hasPermi="['keep:gym:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
					v-hasPermi="['keep:gym:edit']">修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
					@click="handleDelete" v-hasPermi="['keep:gym:remove']">删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
					v-hasPermi="['keep:gym:export']">导出</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="gymList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="健身馆id" align="center" prop="id" />
			<el-table-column label="健身馆名称" align="center" prop="gymName" />
			<el-table-column label="电话" align="center" prop="phone" />
			<el-table-column label="地址" align="center" prop="location" />
			<el-table-column label="邮箱" align="center" prop="email" />
			<el-table-column label="排序" align="center" prop="sort" />
			<el-table-column label="是否开放" align="center" prop="state">
				<template slot-scope="scope">
					<dict-tag :options="dict.type.sys_gym_open" :value="scope.row.state" />
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
						v-hasPermi="['keep:gym:edit']">修改</el-button>
					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
						v-hasPermi="['keep:gym:remove']">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
			@pagination="getList" />

		<!-- 添加或修改健身馆对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="健身馆名称" prop="gymName">
					<el-input v-model="form.gymName" placeholder="请输入健身馆名称" />
				</el-form-item>
				<el-form-item label="场馆介绍">
					<div class="quill_div"><quill-editor v-model="form.gymIntro"></quill-editor></div>
				</el-form-item>
				<el-form-item label="电话" prop="phone">
					<el-input v-model="form.phone" placeholder="请输入电话" />
				</el-form-item>
				<el-form-item label="图片地址" prop="picture">
					<image-upload v-model="form.picture" />
				</el-form-item>
				<!-- 	<el-form-item label="地址" prop="location">
					<el-input v-model="form.location" placeholder="请输入地址" />
				</el-form-item>
				<el-form-item label="经度" prop="longitude">
					<el-input v-model="form.longitude" placeholder="请输入经度" />
				</el-form-item>
				<el-form-item label="纬度" prop="latitude">
					<el-input v-model="form.latitude" placeholder="请输入纬度" />
				</el-form-item> -->

				<el-form-item label="地址：" prop="location">
					<el-autocomplete style="width: 100%" v-model="form.location" :fetch-suggestions="querySearchAsync"
						:trigger-on-focus="false" placeholder="请输入地址" clearable @select="handleSelect">
						<template slot-scope="{ item }">
							<i class="el-icon-search fl mgr10" />
							<div style="overflow: hidden">
								<div class="title">{{ item.title }}</div>
								<span class="address ellipsis">{{ item.address }}</span>
							</div>
						</template>
					</el-autocomplete>
				</el-form-item>
				<el-form-item label="地图定位：">
					<div id="map-container" style="width: 100%; height: 300px" />
				</el-form-item>
				<el-form-item label="经度：">
					<el-input v-model="form.longitude" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="维度：">
					<el-input v-model="form.latitude" autocomplete="off"></el-input>
				</el-form-item>

				<span slot="footer" class="dialog-footer">
					<el-button @click="dialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
				</span>

				<!-- 111111111111111111111111 -->
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="form.email" placeholder="请输入邮箱" />
				</el-form-item>
				<el-form-item label="人数" prop="number">
					<el-input v-model="form.number" placeholder="请输入人数" />
				</el-form-item>
				 <el-form-item label="是否开放" prop="state">
				          <el-radio-group v-model="form.state">
				            <el-radio
				              v-for="dict in dict.type.sys_gym_open"
				              :key="dict.value"
				              :label="parseInt(dict.value)"
				            >{{dict.label}}</el-radio>
				          </el-radio-group>
				        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import loadBMap from '@/utils/loadBMap.js'
	import {
		listGym,
		getGym,
		delGym,
		addGym,
		updateGym
	} from "@/api/keep/gym";

	export default {
		name: "Gym",
		dicts: ['sys_gym_open'],
		data() {
			return {
				// 地图实例
				map: null,
				// Marker实例
				mk: null,
				// 定时器
				initMapeq: null,
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 健身馆表格数据
				gymList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					gymName: null,
					location: null,
					state: null,
				},
				// 表单参数
				form: {},
				// 表单校验
				rules: {}
			};
		},
		created() {
			this.getList();
		},
		mounted() {
			// 页面加载完之后，加载百度地图
			// 加载引入BMap
			loadBMap('D1JnEbfWg9dYMyynj5MSM6JjFmY1XsYX') - 需要申请主页文章有
		},
		methods: {
			/** 查询健身馆列表 */
			getList() {
				this.loading = true;
				listGym(this.queryParams).then(response => {
					this.gymList = response.rows;

					this.total = response.total;
					this.loading = false;
				});
			},
			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
			// 表单重置
			reset() {
				this.form = {
					id: null,
					gymName: null,
					gymIntro: null,
					phone: null,
					picture: null,
					location: null,
					longitude: null,
					latitude: null,
					email: null,
					number: null,
					sort: null,
					score: null,
					state: null,
					del: null
				};
				this.resetForm("form");
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.id)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			/** 新增按钮操作 */
			handleAdd() {
				this.reset();
				this.open = true;
				this.title = "添加健身馆";
				// 加载地图
				this.getbaidu()
			},
			// 加载地图方法
			getbaidu() {
				this.showDialog = true
				this.initMapeq = setInterval(() => {
					if (this.initMap()) {
						clearInterval(this.initMapeq)
					}
				})
			},
			// 百度地图封装方法
			// 初始化地图
			initMap() {
				try {
					var that = this
					// 1、挂载地图
					// 创建地图实例
					this.map = new BMap.Map('map-container')
					// 设置中心经纬度  这里我们使用BMapGL命名空间下的Point类来创建一个坐标点。Point类描述了一个地理坐标点，其中120.872845表示经度，32.021089表示纬度。（为南通濠河风景区坐标） 作者：星银色飞行船
					var point = new BMap.Point(
						this.form.longitude || 116.41338729034514,
						this.form.latitude || 39.910923647957596
					)
					// 3.在创建地图实例后，我们需要对其进行初始化，BMapGL.Map.centerAndZoom()方法要求设置中心点坐标和地图级别。 地图必须经过初始化才可以执行其他操作
					this.map.centerAndZoom(point, 14)
					// 滚轮缩放
					this.map.enableScrollWheelZoom()
					// 3、设置图像标注并绑定拖拽标注结束后事件
					this.mk = new BMap.Marker(point, {
						enableDragging: true
					})
					this.map.addOverlay(this.mk)
				} catch (err) {
					return false
				}
				// 4、添加（右上角）平移缩放控件
				this.map.addControl(
					new BMap.NavigationControl({
						anchor: BMAP_ANCHOR_TOP_RIGHT,
						type: BMAP_NAVIGATION_CONTROL_SMALL
					})
				)
				// 7、绑定点击地图任意点事件
				this.map.addEventListener('click', function(e) {
					console.log('点击了', e)
					that.getAddrByPoint(e.point)
				})
				return true
			},
			// 2、逆地址解析函数 根据坐标点获取详细地址  point   百度地图坐标点，必传
			getAddrByPoint(point) {
				var that = this
				var geco = new BMap.Geocoder()
				geco.getLocation(point, function(res) {
					// console.log(res);
					that.mk.setPosition(point)
					that.map.panTo(point)
					that.form.location = res.address
					that.form.longitude = res.point.lng
					that.form.latitude = res.point.lat
				})
			},
			// 8-1、地址搜索
			querySearchAsync(str, cb) {
				// 根据状态码
				var options = {
					onSearchComplete: function(res) {
						var s = []
						if (local.getStatus() == BMAP_STATUS_SUCCESS) {
							for (var i = 0; i < res.getCurrentNumPois(); i++) {
								s.push(res.getPoi(i))
							}
							cb(s)
						} else {
							cb(s)
						}
					}
				}
				var local = new BMap.LocalSearch(this.map, options)
				local.search(str)
			},
			// 8-2、选择地址
			handleSelect(item) {
			  this.form.location = item.address + item.title;
			  console.log(item);

			  // 使用 parseFloat 确保经纬度为浮点数
			  this.form.longitude = parseFloat(item.point.lng);
			  this.form.latitude = parseFloat(item.point.lat);


			  console.log('lng', this.form.longitude);
			  console.log('lat', this.form.latitude);

			  this.map.clearOverlays();
			  this.mk = new BMap.Marker(item.point);
			  this.map.addOverlay(this.mk);
			  this.map.panTo(item.point);
			}
,
			// 111111111111111111111
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset();
				const id = row.id || this.ids
				getGym(id).then(response => {
					this.form = response.data;
					this.open = true;
					this.title = "修改健身馆";
				});
			},
			/** 提交按钮 */
			submitForm() {
				this.$refs["form"].validate(valid => {
					if (valid) {
						if (this.form.id != null) {
							updateGym(this.form).then(response => {
								this.$modal.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							});
						} else {
							addGym(this.form).then(response => {
								this.$modal.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							});
						}
					}
				});
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const ids = row.id || this.ids;
				this.$modal.confirm('是否确认删除健身馆编号为"' + ids + '"的数据项？').then(function() {
					return delGym(ids);
				}).then(() => {
					this.getList();
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			},
			/** 导出按钮操作 */
			handleExport() {
				this.download('keep/gym/export', {
					...this.queryParams
				}, `gym_${new Date().getTime()}.xlsx`)
			}
		}
	};
</script>

<style lang="scss" scoped>
	.conter {

		// 去除百度地图的图标
		::v-deep .anchorBL {
			display: none !important;
		}
	}
	  // .quill-editor {
	  //   height: 400px;
	  //   margin-bottom: 40px;
	  // }
</style>
